package com.humble.vichatbackend.config.datasource;


import com.humble.vichatbackend.common.SearchRequest;
import com.humble.vichatbackend.model.domain.Team;
import com.humble.vichatbackend.model.elastic.domain.ElasticTeam;
import com.humble.vichatbackend.service.elastic.TeamRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.Criteria;
import org.springframework.data.elasticsearch.core.query.CriteriaQuery;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

@Component
public class TeamDataSource implements DataSource<ElasticTeam>{
    @Autowired
    private ElasticsearchOperations elasticsearchOperations;

    @Override
    public Page<ElasticTeam> doSearch(SearchRequest searchRequest) {
        String context = searchRequest.getContext();
        int pageSize = searchRequest.getPageSize();
        int pageNum = searchRequest.getPageNum();
        Criteria criteria = new Criteria("name").is(context)
                .or("description").is(context);
        PageRequest pageRequest = PageRequest.of(pageNum, pageSize);
        CriteriaQuery criteriaQuery = new CriteriaQuery(criteria,pageRequest);
        //整合结果
        SearchHits<ElasticTeam> searchResult = elasticsearchOperations.search(criteriaQuery, ElasticTeam.class);
        List<ElasticTeam> collect = searchResult.stream().map(SearchHit::getContent).collect(Collectors.toList());
        return new PageImpl<>(collect);
    }
}
